package com.oocl.communicator.impl;

import java.io.IOException;
import java.io.ObjectInputStream;

import javax.swing.JOptionPane;

import com.oocl.communicator.Receiver;
import com.oocl.constant.LogLevel;
import com.oocl.constant.ProtocolType;
import com.oocl.parser.ProtocolParser;
import com.oocl.pojo.Protocol;
import com.oocl.util.LogUtil;
import com.oocl.util.ResourceReleaser;
import com.oocl.view.ChatFrame;
import com.oocl.view.Login;

/**
 * 
 * @author ZHANGAR
 *
 */
public class ReceiverImpl extends Thread implements Receiver {
	private ObjectInputStream in;
	ProtocolParser chatParser;
	Login login;
	
	boolean isRunning = true;
	
	public ReceiverImpl(ObjectInputStream in,ChatFrame frame) {
		this.in = in;
		chatParser = frame;
	}

	@Override
	public void run() {
		receive(in);
	}

	@Override
	public void receive(ObjectInputStream in) {
		try {
			while(isRunning) {
				Protocol pro = (Protocol)in.readObject();
				LogUtil.log("receive a protocol package!"+pro, LogLevel.INFO);
				if(pro==null)
					continue;
				switch (pro.getType()) {
				case ProtocolType.LAYOUT:
					chatParser.parseLoyout(pro);
					break;
				case ProtocolType.PRIVATE_TALK:
					chatParser.parsePrivateTalk(pro);
					break;
				case ProtocolType.GROUP_SHAKE:
					chatParser.parseGroupShake(pro);
					break;
				case ProtocolType.GROUPE_TALK:
					chatParser.parseGroupTalk(pro);
					break;
				case ProtocolType.PRIVATE_SHAKE:
					chatParser.parsePrivateShake(pro);
					break;
				case ProtocolType.USER_LAYOUT:
					chatParser.parseUserLoyout(pro);
					break;
				case ProtocolType.USER_LOGIN:
					chatParser.parseUserLogin(pro);
					break;
				default:
					break;
				}
			}
		} catch (ClassNotFoundException e) {
			LogUtil.log("ClassNotFoundException!"+e.getMessage(), LogLevel.ERROR);
			JOptionPane.showMessageDialog(null, "找不到服务器连接", "Tip", JOptionPane.ERROR_MESSAGE);
			ResourceReleaser.release(null, in, null);
		} catch (IOException e) {
			LogUtil.log("IOException!"+e.getMessage(), LogLevel.ERROR);
			JOptionPane.showMessageDialog(null, "找不到服务器连接", "Tip", JOptionPane.ERROR_MESSAGE);
			ResourceReleaser.release(null, in, null);
		}
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}
	
	
}
